﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

namespace Metozis.SimpleXMLSerialization.Contacts
{
    public class ContactsRepository : IRepository
    {
        private readonly string _path;

        public ContactsRepository(string path)
        {
            _path = path;
        }

        public void ReadXml()
        {
            var serializer = new XmlSerializer(typeof (ContactList));

            var reader = new FileStream(_path, FileMode.Open, FileAccess.Read, FileShare.Read);

            var contacts = (IEnumerable<Contact>) serializer.Deserialize(reader);

            reader.Close();
            Console.WriteLine("   Preview of XML file created   ");
            Console.WriteLine("{0,15} {1,15} {2,15}", "Name    ", "Address  ", "Telephone  ");
            foreach (Contact contact in contacts)
            {
                Console.WriteLine("{0,15} {1,15} {2,15}", contact.Name, contact.Address, contact.Telephone);
            }
            Console.WriteLine("");
        }

        public void WriteXml()
        {
            var serializer = new XmlSerializer(typeof (ContactList));

            var contacts = new ContactList();

            contacts.Add(new Contact {Name = "Costas  ", Address = "Illnau   ", Telephone = "+4121313223"});
            contacts.Add(new Contact {Name = "Bill    ", Address = "Rotkreuz ", Telephone = "+4121313229"});
            contacts.Add(new Contact {Name = "Dimitris", Address = "Athens   ", Telephone = "+3021313278"});
            contacts.Add(new Contact {Name = "Stelios ", Address = "Preveza  ", Telephone = "+3021313236"});
            contacts.Add(new Contact {Name = "Jiannis ", Address = "Hinwill  ", Telephone = "+4121313245"});
            contacts.Add(new Contact {Name = "Sotiris ", Address = "Peristeri", Telephone = "+3021313228"});

            TextWriter writer = new StreamWriter(_path);
            serializer.Serialize(writer, contacts);

            writer.Close();
        }
    }
}